<?php
class UserPost
{
	private $db;

	public function __construct($db)
	{
		$this->db = $db;
	}

	/**
	 * 从令牌中获取用户ID
	 */
	public function getUserIdFromToken($token)
	{
		try {
			$stmt = $this->db->prepare("SELECT user_id FROM user_tokens WHERE token = ? AND expires_at > NOW()");
			$stmt->execute([$token]);
			$result = $stmt->fetch(PDO::FETCH_ASSOC);

			return $result ? $result['user_id'] : null;
		} catch (PDOException $e) {
			error_log("[UserPost Model] 令牌查询错误: " . $e->getMessage());
			throw new Exception("验证用户令牌失败");
		}
	}

	/**
	 * 根据用户ID获取攻略帖
	 */
	public function getPostsWithUserInfo($userId)
	{
		try {
			$stmt = $this->db->prepare("SELECT * FROM posts WHERE posts.user_id = ? ORDER BY posts.created_at DESC;");
			$stmt->execute([$userId]);

			return $stmt->fetchAll(PDO::FETCH_ASSOC);
		} catch (PDOException $e) {
			error_log("[UserPost Model] 用户帖子查询错误: " . $e->getMessage());
			throw new Exception("获取用户帖子失败");
		}
	}


	/**
	 * 根据用户ID获取讨论帖
	 */
	public function getTopicsWithUserInfo($userId)
	{
		try {
			$stmt = $this->db->prepare("SELECT * FROM topics WHERE topics.user_id = ? ORDER BY topics.created_at DESC;");
			$stmt->execute([$userId]);

			return $stmt->fetchAll(PDO::FETCH_ASSOC);
		} catch (PDOException $e) {
			error_log("[UserPost Model] 用户帖子查询错误: " . $e->getMessage());
			throw new Exception("获取用户帖子失败");
		}
	}


	/**
	 * 删除攻略帖
	 */
	public function deletePost($postId, $userId = null)
	{
		try {
			$sql = "DELETE FROM posts WHERE id = ?";
			$params = [$postId];

			// 如果提供了用户ID，则验证帖子属于该用户
			if ($userId) {
				$sql .= " AND user_id = ?";
				$params[] = $userId;
			}

			$stmt = $this->db->prepare($sql);
			$stmt->execute($params);

			return $stmt->rowCount() > 0;
		} catch (PDOException $e) {
			error_log("[UserPost Model] 删除帖子错误: " . $e->getMessage());
			throw new Exception("删除帖子失败");
		}
	}

	/**
	 * 删除讨论帖
	 */
	public function deleteTopic($topicId, $userId = null)
	{
		try {
			$sql = "DELETE FROM topics WHERE id = ?";
			$params = [$topicId];

			// 如果提供了用户ID，则验证讨论帖属于该用户
			if ($userId) {
				$sql .= " AND user_id = ?";
				$params[] = $userId;
			}

			$stmt = $this->db->prepare($sql);
			$stmt->execute($params);

			return $stmt->rowCount() > 0;
		} catch (PDOException $e) {
			error_log("[UserPost Model] 删除讨论帖错误: " . $e->getMessage());
			throw new Exception("删除讨论帖失败");
		}
	}
}